<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="调拨单号" prop="transferNo">
        <el-input
          v-model="queryParams.transferNo"
          placeholder="请输入调拨单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="调拨状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择调拨状态"
          clearable
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['wms:transfer:add']"
        >新建调拨</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:transfer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:transfer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-check"
          :disabled="single"
          @click="handleApprove"
          v-hasPermi="['wms:transfer:approve']"
        >审批</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['wms:transfer:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="transferList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="调拨单号" align="center" prop="transferNo" />
      <el-table-column label="源仓库" align="center" prop="fromWarehouseName" />
      <el-table-column label="目标仓库" align="center" prop="toWarehouseName" />
      <el-table-column label="物料数量" align="center" prop="materialCount" />
      <el-table-column label="调拨状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applicant" />
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['wms:transfer:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:transfer:edit']"
            v-if="scope.row.status === '0'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleExecute(scope.row)"
            v-hasPermi="['wms:transfer:execute']"
            v-if="scope.row.status === '1'"
          >执行</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleCancel(scope.row)"
            v-hasPermi="['wms:transfer:cancel']"
            v-if="scope.row.status === '0' || scope.row.status === '1'"
          >取消</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改调拨对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="源仓库" prop="fromWarehouseId">
              <el-select
                v-model="form.fromWarehouseId"
                placeholder="请选择源仓库"
                @change="handleFromWarehouseChange"
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标仓库" prop="toWarehouseId">
              <el-select
                v-model="form.toWarehouseId"
                placeholder="请选择目标仓库"
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                  :disabled="item.warehouseId === form.fromWarehouseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="调拨原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入调拨原因" />
        </el-form-item>
        
        <!-- 调拨物料列表 -->
        <el-divider content-position="left">调拨物料清单</el-divider>
        <el-table
          :data="form.materialList"
          border
          style="width: 100%; margin-bottom: 20px"
        >
          <el-table-column label="物料编码" prop="materialCode" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.materialCode"
                placeholder="请输入物料编码"
                @blur="handleMaterialSelect(scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column label="物料名称" prop="materialName" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.materialName"
                placeholder="请输入物料名称"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="调拨数量" prop="quantity" width="120">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.quantity"
                :min="1"
                :step="1"
              />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" width="80">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.unit"
                placeholder="单位"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="当前库存" prop="currentStock" width="120">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.currentStock"
                placeholder="当前库存"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleMaterialDelete(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleMaterialAdd"
          style="margin-bottom: 20px"
        >添加物料</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTransfer, getTransfer, addTransfer, updateTransfer, deleteTransfer, approveTransfer, executeTransfer, cancelTransfer } from "@/api/wms";
import { listWarehouse } from "@/api/wms";
import { getMaterialByCode } from "@/api/wms";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "Transfer",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 调拨表格数据
      transferList: [],
      // 仓库选项
      warehouseOptions: [],
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transferNo: undefined,
        materialCode: undefined,
        status: undefined,
        beginTime: undefined,
        endTime: undefined
      },
      // 表单参数
      form: {
        fromWarehouseId: undefined,
        toWarehouseId: undefined,
        reason: undefined,
        materialList: []
      },
      // 表单校验
      rules: {
        fromWarehouseId: [
          { required: true, message: "请选择源仓库", trigger: "change" }
        ],
        toWarehouseId: [
          { required: true, message: "请选择目标仓库", trigger: "change" }
        ],
        reason: [
          { required: true, message: "请输入调拨原因", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts();
    this.getWarehouseList();
  },
  methods: {
    /** 查询调拨列表 */
    getList() {
      this.loading = true;
      if (this.dateRange != null && this.dateRange.length === 2) {
        this.queryParams.beginTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      }
      listTransfer(this.queryParams).then(response => {
        this.transferList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取数据字典
    getDicts() {
      getDicts("wms_transfer_status").then(response => {
        this.statusOptions = response.data;
      });
    },
    // 获取仓库列表
    getWarehouseList() {
      listWarehouse().then(response => {
        this.warehouseOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        transferId: undefined,
        fromWarehouseId: undefined,
        toWarehouseId: undefined,
        reason: undefined,
        materialList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.transferId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建调拨单";
      // 默认添加一行空物料
      this.form.materialList = [{
        materialCode: "",
        materialName: "",
        quantity: 1,
        unit: "",
        currentStock: 0
      }];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const transferId = row.transferId || this.ids;
      getTransfer(transferId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改调拨单";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const transferId = row.transferId;
      this.$router.push({ path: "/wms/transfer/detail", query: { transferId: transferId } });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const transferIds = row.transferId || this.ids;
      this.$modal.confirm('是否确认删除调拨单号为"' + transferIds + '"的数据项？').then(function() {
        return deleteTransfer(transferIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 审批按钮操作 */
    handleApprove(row) {
      const transferId = row.transferId || this.ids[0];
      this.$prompt('请输入审批意见', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '审批意见不能为空'
      }).then(({ value }) => {
        approveTransfer(transferId, value).then(response => {
          this.$modal.msgSuccess("审批成功");
          this.getList();
        });
      }).catch(() => {});
    },
    /** 执行按钮操作 */
    handleExecute(row) {
      const transferId = row.transferId;
      this.$modal.confirm('确认执行调拨单号为"' + transferId + '"的调拨操作？').then(function() {
        return executeTransfer(transferId);
      }).then(() => {
        this.$modal.msgSuccess("执行成功");
        this.getList();
      }).catch(() => {});
    },
    /** 取消按钮操作 */
    handleCancel(row) {
      const transferId = row.transferId;
      this.$prompt('请输入取消原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '取消原因不能为空'
      }).then(({ value }) => {
        cancelTransfer(transferId, value).then(response => {
          this.$modal.msgSuccess("取消成功");
          this.getList();
        });
      }).catch(() => {});
    },
    /** 源仓库变更 */
    handleFromWarehouseChange(val) {
      // 清空物料列表
      this.form.materialList = [];
    },
    /** 添加物料 */
    handleMaterialAdd() {
      this.form.materialList.push({
        materialCode: "",
        materialName: "",
        quantity: 1,
        unit: "",
        currentStock: 0
      });
    },
    /** 删除物料 */
    handleMaterialDelete(index) {
      this.form.materialList.splice(index, 1);
    },
    /** 物料选择 */
    handleMaterialSelect(index) {
      const materialCode = this.form.materialList[index].materialCode;
      if (!materialCode) return;
      
      if (!this.form.fromWarehouseId) {
        this.$modal.msgError("请先选择源仓库");
        return;
      }

      getMaterialByCode(this.form.fromWarehouseId, materialCode).then(response => {
        if (response.data) {
          this.form.materialList[index] = {
            ...this.form.materialList[index],
            materialName: response.data.materialName,
            unit: response.data.unit,
            currentStock: response.data.quantity
          };
        } else {
          this.$modal.msgError("未找到该物料");
          this.form.materialList[index].materialCode = "";
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 校验物料列表
          if (this.form.materialList.length === 0) {
            this.$modal.msgError("请至少添加一条物料");
            return;
          }
          
          for (let i = 0; i < this.form.materialList.length; i++) {
            const item = this.form.materialList[i];
            if (!item.materialCode) {
              this.$modal.msgError(`第${i+1}行物料编码不能为空`);
              return;
            }
            if (item.quantity <= 0) {
              this.$modal.msgError(`第${i+1}行调拨数量必须大于0`);
              return;
            }
            if (item.quantity > item.currentStock) {
              this.$modal.msgError(`第${i+1}行调拨数量不能大于当前库存`);
              return;
            }
          }

          if (this.form.transferId != null) {
            updateTransfer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTransfer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/transfer/export', {
        ...this.queryParams
      }, `transfer_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>